//
//  mm_popupViewController.m
//  HondaPro_2
//
//  Created by Eric on 13-7-2.
//  Copyright (c) 2013年 glendale. All rights reserved.
//

#import "mm_popupViewController.h"

#import "picRecodeViewController.h"

@interface mm_popupViewController ()

//创建控件
-(void)createControls;

//button 的回调方法
-(void)captureBtnPressed:(UIButton *)sender;

@end

@implementation mm_popupViewController

@synthesize numsText;
@synthesize remarksText;
@synthesize bianhaoDisLbl = _bianhaoDisLbl;
@synthesize leixingDisLbl = _leixingDisLbl;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        
//        [self.view setFrame:CGRectMake(163, 100, 450, 200)];
        self.view.frame = CGRectMake(0, 0, 500, 600);
        
        self.view.frame =CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height);
        
        [self createControls];
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    //初始化存图片的临时列表
    [MainMenuDataModel sharedMainMenuDataModel].arrOutCheckImageNameListTmp = nil;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - 创建控件

-(void)createControls
{
    //创建lbl
    UILabel *bianhaoLbl = [[UILabel alloc] initWithFrame:CGRectMake(10, 10+120, 50, 30)];
    bianhaoLbl.backgroundColor = [UIColor clearColor];
    bianhaoLbl.text = @"编号：";
    bianhaoLbl.textColor = [UIColor grayColor];
    bianhaoLbl.font = [UIFont fontWithName:@"ArialMT" size:16];
    [self.view addSubview:bianhaoLbl];
    
    UILabel *leixingLbl = [[UILabel alloc] initWithFrame:CGRectMake(10, 50+120, 50, 30)];
    leixingLbl.backgroundColor = [UIColor clearColor];
    leixingLbl.text = @"类型：";
    leixingLbl.textColor = [UIColor grayColor];
    leixingLbl.font = [UIFont fontWithName:@"ArialMT" size:16];
    [self.view addSubview:leixingLbl];
    
    UILabel *shuliangLbl = [[UILabel alloc] initWithFrame:CGRectMake(10, 90+120, 50, 30)];
    shuliangLbl.backgroundColor = [UIColor clearColor];
    shuliangLbl.text = @"数量：";
    shuliangLbl.textColor = [UIColor grayColor];
    shuliangLbl.font = [UIFont fontWithName:@"ArialMT" size:16];
    [self.view addSubview:shuliangLbl];
    
    UILabel *beizhuLbl = [[UILabel alloc] initWithFrame:CGRectMake(10, 130+120, 50, 30)];
    beizhuLbl.backgroundColor = [UIColor clearColor];
    beizhuLbl.text = @"备注：";
    beizhuLbl.textColor = [UIColor grayColor];
    beizhuLbl.font = [UIFont fontWithName:@"ArialMT" size:16];
    [self.view addSubview:beizhuLbl];
    
    self.bianhaoDisLbl = [[UILabel alloc] initWithFrame:CGRectMake(61, 10+120, 300, 30)];
    self.bianhaoDisLbl.backgroundColor = [UIColor clearColor];
    self.bianhaoDisLbl.text = @"xxx";
    self.bianhaoDisLbl.textColor = [UIColor grayColor];
    self.bianhaoDisLbl.font = [UIFont fontWithName:@"ArialMT" size:16];
    [self.view addSubview:self.bianhaoDisLbl];
    
    self.leixingDisLbl = [[UILabel alloc] initWithFrame:CGRectMake(61, 50+120, 380, 30)];
    self.leixingDisLbl.backgroundColor = [UIColor clearColor];
    self.leixingDisLbl.text = @"xxx";
    self.leixingDisLbl.textColor = [UIColor grayColor];
    self.leixingDisLbl.font = [UIFont fontWithName:@"ArialMT" size:16];
    [self.view addSubview:self.leixingDisLbl];
    
    //创建Text
    numsText = [[UITextField alloc] initWithFrame:CGRectMake(61, 90+120, 380, 30)];
    numsText.borderStyle = UITextBorderStyleLine;
    numsText.textColor = [UIColor grayColor];
    numsText.font = [UIFont fontWithName:@"ArialMT" size:16];
    numsText.text = @"1";
    [self.view addSubview:numsText];
    
    remarksText = [[UITextView alloc] initWithFrame:CGRectMake(61, 130+120, 380, 60)];
    remarksText.layer.borderColor = [UIColor blackColor].CGColor;
    remarksText.layer.borderWidth = 1.0;
    remarksText.textColor = [UIColor grayColor];
    remarksText.font = [UIFont fontWithName:@"ArialMT" size:16];
    [self.view addSubview:remarksText];
    
    //创建Button
    UIButton *captureBtn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    [captureBtn setTitle:@"拍照" forState:UIControlStateNormal];
    [captureBtn setFrame:CGRectMake(362, 10+120, 60, 30)];
    [captureBtn addTarget:self action:@selector(captureBtnPressed:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:captureBtn];
}

#pragma mark - button 的回调方法

//拍照按钮的回调方法
-(void)captureBtnPressed:(UIButton *)sender
{
//    NSLog(@"captureBtnPressed !!!");
    
    UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
    [imagePicker setSourceType:UIImagePickerControllerSourceTypeCamera];
    
    
    
    [imagePicker setDelegate:self];
//    NSLog(@"picbtn=====");
    
    [imagePicker setModalPresentationStyle:UIModalPresentationFullScreen];
    [imagePicker setModalTransitionStyle:UIModalTransitionStyleCoverVertical];
    
    [self presentViewController:imagePicker animated:YES completion:nil];
}

-(UIImage *)resizeCImage:(UIImage *)image toSize:(CGSize)size
{
    float width = size.width;
    float height = size.height;
    
//    NSLog(@"WIDTH IN RESIZED FUN ====%f",width);
    
    UIGraphicsBeginImageContext(size);
    
    float x = 0.0f;
    float y = 0.0f;
    
    
    CGRect rect = CGRectMake(x, y, width, height);
    
    [image drawInRect: rect];
    
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    
    UIGraphicsEndImageContext();
    
    return newImage;
}

-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    [picker setVideoQuality:UIImagePickerControllerQualityTypeHigh];
    
    UIImage *imageimage = [info valueForKey:UIImagePickerControllerOriginalImage];
    UIImage *image = [picRecodeViewController imageWithImageSimple:imageimage scaledToSize:CGSizeMake(320, 240)];
    
    /*
     上传图片的逻辑：（1）每一次拍照完毕，就调用上传图片的接口
     */
    
    NSData *imgData = UIImageJPEGRepresentation(image, 1.0);
    
    //添加消息
    [self addAllObserver];
    
    webService *web=[[webService alloc] init];
    web.methodName = MM_ADD_OUT_CHECK_PIC_;
    [web picAndRecordPostSharedRequest:web.methodName postData:imgData];
    
    [self dismissViewControllerAnimated:YES completion:nil];
}

//保存文件至沙盒目录
- (void) saveImage:(UIImage *)currentImage withName:(NSString *)imageName
{
    
    NSData *imageData = UIImageJPEGRepresentation(currentImage, 0.5);
    // 获取沙盒目录
    
    NSString *fullPath = [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:imageName];
    // 将图片写入文件
    
    [imageData writeToFile:fullPath atomically:NO];
}

-(NSString*)imageFileTextPath:(NSString*)imageName{
    
    NSString *documentPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    
    NSString *imgStr = [NSString stringWithFormat:@"/%@",imageName];
//    NSLog(@"path==%@",[documentPath stringByAppendingPathComponent:imgStr]);
    
    return [documentPath stringByAppendingPathComponent:imgStr];
}

- (BOOL)writeImage:(UIImage*)image toFileAtPath:(NSString*)aPath{
    if ((image == nil) || (aPath == nil) || ([aPath isEqualToString:@""]))
        return NO;
    @try
    {
        
        NSData *imageData = nil;
        NSString *ext = [aPath pathExtension];
        if ([ext isEqualToString:@"png"])
        {
            imageData = UIImagePNGRepresentation(image);
        }
        else
        {
            // the rest, we write to jpeg
            // 0. best, 1. lost. about compress.
//            NSLog(@"++++++++");
            imageData = UIImageJPEGRepresentation(image, 1.0);
            
        }
        
        if ((imageData == nil) || ([imageData length] <= 0))
            return NO;
        
        [imageData writeToFile:aPath atomically:NO];
        return YES;
    }
    @catch (NSException *e)
    {
//        NSLog(@"create thumbnail exception.");
    }
    return NO;
}

#pragma mark - 设置数据模型里边的部分数据

/*
 操作：
 （1）用本类中的两个text值更新数据模型中对应的两个字符串属性
 */

-(void)setSeveralData
{
    mm_picRecodeDataModel *modelIns = [mm_picRecodeDataModel sharedModelIns];
    
    modelIns.numberStr = numsText.text;
    modelIns.remarksStr = remarksText.text;
}

//注册消息
-(void)addAllObserver
{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(addImgToServer:) name:MM_ADD_OUT_CHECK_PIC_ object:nil];
}

//移除消息
-(void)removeAllObserver
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

//图片上传接口的回调方法
-(void)addImgToServer:(NSNotification *)notification
{
    /*
     {"picName":"20130830210757.jpg","error_code":0,"error_msg":""}
     */
    NSDictionary *theJson = [NSJSONSerialization JSONObjectWithData:(NSData*)notification.object options:NSJSONReadingMutableLeaves error:Nil];
    NSLog(@"%@",theJson);
    
    NSString *picNameStr = [theJson objectForKey:@"picName"];
    NSString *errorCodeStr = [NSString stringWithFormat:@"%@",[theJson objectForKey:@"error_code"]];
    NSString *errorMsgStr = [theJson objectForKey:@"error_msg"];
    /*
     （1）如果上传成功，获取返回的图片名称，并且将该名称添加入临时存放图片的列表中；否则提示错误信息，return；
     */
    
    /*
     "imageNameList"://imageName改为imageNameList
     [
     {"imageName":"2013.jpg"},
     {"imageName":"2014.jpg"}
     ],
     */
    
    if (![errorCodeStr isEqualToString:@"0"])
    {
        //提示保存失败，return
        
        UIAlertView *alerVeiw = [[UIAlertView alloc] initWithTitle:@"图片保存失败" message:errorMsgStr delegate:self cancelButtonTitle:@"我知道了" otherButtonTitles:nil, nil];
        [alerVeiw show];
        
        return;
    }
    MainMenuDataModel *modelIns = [MainMenuDataModel sharedMainMenuDataModel];
    if (nil == modelIns.arrOutCheckImageNameListTmp)
    {
        modelIns.arrOutCheckImageNameListTmp = [NSMutableArray array];
    }
    [modelIns.arrOutCheckImageNameListTmp addObject:[NSDictionary dictionaryWithObjectsAndKeys:picNameStr,MM_OUT_CHECK_IMAGE_NAME_KEY_STR_, nil]];
}

- (IBAction)okBtnPressed:(UIButton *)sender
{
    //发送消息给缺陷标记界面
    [[NSNotificationCenter defaultCenter] postNotificationName:MM_FAULTY_POINT_QUIT_POP_UP_VIEW_MSG_ object:nil];
}

@end
